$(function () {
    $("#questionNameDetail").html("<"+
        getCookie("nameOfQuestionnaire") + ">答题情况明细");
    var oTable = new TableInit();
    oTable.Init();

    //传回用户名
    var da = {
        "user": getCookie("userName")
    };
    //添加下拉选择问卷
    var selectContent = ''; //下拉选择内容
    jQuery.ajax({
        type: "POST",
        url: httpRequestUrl + "/queryAllQuestionnaireByCreated",
        data: JSON.stringify(da),
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            for (var i = 0; i < result.data.length; i++) {
                selectContent += '<option value="' + result.data[i].id + '">' +
                    result.data[i].questionName + '</option>'
            }
            $("#ddlActivitynew").html(selectContent)
            $("#ddlActivitynew option[value='" + getCookie("questionId") + "']").attr(
                "selected", "selected");
        }
    });
});

//    切换问卷
$("#ddlActivitynew").change(function () {
    var activity = $(this).val();
    var nameQuestion = $(this)[0].selectedOptions[0].innerHTML;
    if (activity) {
        deleteCookie("questionId");
        setCookie("questionId", activity)
        deleteCookie("nameOfQuestionnaire");
        setCookie("nameOfQuestionnaire", nameQuestion)
        $("#questionNameDetail").html("<"+
            getCookie("nameOfQuestionnaire") + ">答题情况明细");
        getQuestionnaireAboutSchool();
    }
})

// XXX问卷答题情况明细
function getQuestionnaireAboutSchool() {
    $("#countTable").bootstrapTable('refresh');
}

function TableInit() {

    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#countTable').bootstrapTable({
            url: httpRequestUrl + '/queryRecordCountAnswer',         //请求后台的URL（*）
            method: 'POST',                      //请求方式（*）
            striped: true,                      //是否显示行间隔色
            pagination: true,                   //是否显示分页（*）
            //是否启用排序
            sortOrder: "asc",                   //排序方式
            sortStable: true,                   //是否排序
            queryParamsType: '',//默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
            dataType: 'json',
            paginationShowPageGo: true,
            showJumpto: true,
            pageNumber: 1, //初始化加载第一页，默认第一页
            queryParams: queryParams,//请求服务器时所传的参数
            sidePagination: 'server',//指定服务器端分页
            pageSize: 100,//单页记录数
            pageList: [100],//分页步进值
            search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            silent: true,
            showRefresh: false,                  //是否显示刷新按钮
            showToggle: false,
            minimumCountColumns: 2,             //最少允许的列数
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列

            columns: [{
                checkbox: true,
                visible: false
            }, {
                field: 'id',
                title: '序号',
                align: 'center',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
                {
                    field: 'answerName',
                    title: '提交人',
                    align: 'center',
                    /*sortable : true*/
                },
                {
                    field: 'answerBelong',
                    title: '所属学校',
                    align: 'center',
                    /*sortable : true*/
                },
                {
                    field: 'endTime',
                    title: '提交答卷时间',
                    align: 'center',
                    width: '200px',
                    /*sortable : true*/
                },
                {
                    field: 'longTime',
                    title: '所用时间',
                    align: 'center',
                    /*sortable : true*/
                }, {
                    field: 'answerSource',
                    title: '来源',
                    align: 'center',
                    /*sortable : true*/
                }, {
                    field: 'ipAddress',
                    title: '来自ip',
                    align: 'center',
                    /*sortable : true*/
                },
                {
                    field: 'operation',
                    title: '操作',
                    width: '90px',
                    align: 'center',
                    events: operateEvents,//给按钮注册事件
                    formatter: addFunctionAlty//表格中增加按钮
                }],
            responseHandler: function (res) {
                //console.log(res);
                if (res.code === "666") {
                    var answerInfo = res.data.list;
                    var NewData = [];
                    if (answerInfo.length) {
                        for (var i = 0; i < answerInfo.length; i++) {
                            var dataNewObj = {
                                'id': '',
                                "answerName": '',
                                'answerBelong': '',
                                "endTime": '',
                                'longTime': '',
                                'answerSource': '',
                                'ipAddress': '',
                                "uid": "",
                                'ssqid':""
                            };
                            dataNewObj.id = '' + i;
                            dataNewObj.uid= '' +i;
                            dataNewObj.answerName = answerInfo[i].answerName;
                            dataNewObj.answerBelong = answerInfo[i].answerBelong;
                            dataNewObj.endTime = answerInfo[i].endTime;
                            dataNewObj.longTime = answerInfo[i].longTime+"秒";
                            dataNewObj.sqid = answerInfo[i].longTime+"秒";
                            dataNewObj.ssqid = getCookie("questionId");;
                            console.log("阿斯顿很健" + dataNewObj.ssqid);
                            if(answerInfo[i].answerSource === "email"){
                                dataNewObj.answerSource = "邮件";
                            }else if(answerInfo[i].answerSource === "phone"){
                                dataNewObj.answerSource = "手机";
                            }else if(answerInfo[i].answerSource === "link"){
                                dataNewObj.answerSource = "链接";
                            }else{
                                dataNewObj.answerSource = "其他";
                            }
                            dataNewObj.ipAddress = answerInfo[i].ipAddress;
                            console.log(dataNewObj);
                            NewData.push(dataNewObj);
                        }
                        var data = {
                            total: res.data.total,
                            rows: NewData
                        };
                    } else {
                        var data = {
                            rows: NewData
                        };
                    }
                    return data;
                } else {
                    var data = {
                        rows: []
                    };
                    return data;
                }

            }
        });
    };

    // 得到查询的参数
    function queryParams(params) {
        var answerNameOrBelong = $("#keyWord").val();
        answerNameOrBelong = answerNameOrBelong === "" ? null : answerNameOrBelong;
        var questionId = getCookie("questionId");
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            pageNum: params.pageNumber,
            pageSize: params.pageSize,
            questionId: questionId,
            answerNameOrBelong: answerNameOrBelong,
        };
        return JSON.stringify(temp);
    }

    return oTableInit;
}

window.operateEvents = {
    //编辑
    'click #btn_count': function (e, value, row, index) {
        id = row.id;
        $.cookie('questionId', id);
    }
};

// 表格中按钮
function addFunctionAlty(value, row, index) {
    var btnText = '';
//详情
    btnText += "<a href=\"javascript:void(0);\" onclick=\"showDetail("
        + "'" + row.endTime + "', '" + row.ssqid + "'"
        + ")\" style=\" color: #277093;\">详情</a>&nbsp;&nbsp;";
    //删除
    btnText += "<a href=\"javascript:void(0);\" onclick=\"deleteAnswerInfo("
        + "'" + row.id + "'"
        + ")\" style=\" color: #f00;\">删除</a>";//#f9f9f9
    return btnText;
}

function getReport() {

    //下载报告
    $("#countTable").tableExport({
        type: "excel",
        escape: "false",
        fileName: getCookie("nameOfQuestionnaire") + '答题情况明细'
    });

}

//设计问卷
function designQuestionnaire() {
    var ifDesignQuestionnaire = getCookie("ifDesignQuestionnaire");
    if (ifDesignQuestionnaire === "false") {
        layer.msg("问卷处于运行状态或问卷已发布，不可设计问卷", {icon: 2})
    } else {
        $.cookie("QuestionId", getCookie("questionId"));
        window.open('designQuestionnaire.html')
    }
}

//发送问卷
function ifSendQuestionnaire() {
    var ifSendQuestionnaire = getCookie("ifSendQuestionnaire");
    if (ifSendQuestionnaire === "false") {
        layer.msg("问卷处于未发送或暂停的状态，不可发送问卷", {icon: 2})
    } else {
        $.cookie("QuestionId", getCookie("questionId"));
        window.location.href = 'sendQuestionnaire.html';
    }
}

//预览问卷
$('#ctl02_hrefView').click(function () {
    window.open('previewQuestionnaire.html?i=' + getCookie("questionId") + '&e0Rp=preview');
});
//回车事件
$(document).keydown(function (event) {
    if (event.keyCode == 13) {
        getQuestionnaireAboutSchool();
    }
});

//返回主页
function backhome() {
    window.location.href = 'myQuestionnaires.html'
}

//删除答卷信息
function deleteAnswerInfo(id){
    console.log("123");
}
//显示答卷详细信息
function showDetail(id, questionID){

    window.open("http://localhost:8181/#/Tt/" + id + "/" + questionID, "_top");

}

//查看答卷详情表格
function viewAnswerDetail(){
//跳转到答卷详情页面
//     console.log("123");
    window.location.href = 'answerDetail.html';
}
